﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using ThresholdAssistant.Tools;
using ThresholdAssistant.WebAPI.Models;

namespace ThresholdAssistant.WebAPI.Service
{

    public static class ThresholdFileService
    {
        private static string FileDirectory = StaticVar.LogThresholdFile;

        /// <summary>
        /// 创建提醒内容
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static void CreateSms(SmsInfoParam param)
        {
            if (param == null)
                return;

            param.ToJsonStr().LogWriteTxtSingle(param.GroupId);
        }

        /// <summary>
        /// 读取提醒内容
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static SmsInfoParam ReadSms(string groupId, string fileServerPath = "")
        {
            SmsInfoParam param = null;

            if (string.IsNullOrEmpty(groupId))
                return param;

            var json = LogGetTxtSingle(groupId, fileServerPath);
            if (!string.IsNullOrEmpty(json))
                param = json.JsonToObj<SmsInfoParam>();

            return param;
        }

        /// <summary>
        /// 删除提醒内容
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static SmsInfoParam RemoveSms(string groupId, string fileServerPath = "")
        {
            var result = DeleteTxtSingle(groupId, fileServerPath);
            return result;
        }

        /// <summary>
        /// 单文件写入
        /// </summary>
        /// <param name="logContext">要写入的内容</param>
        /// <param name="path">路径</param>
        /// <param name="filename">文件名</param>
        private static void LogWriteTxtSingle(this string logContext, string filename, bool isDelete = false)
        {
            if (string.IsNullOrEmpty(logContext))
                return;
            var dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine + FileDirectory + StaticVar.PathSplitLine;
            if (Directory.Exists(dirBase) == false)
                Directory.CreateDirectory(dirBase);

            filename = dirBase + filename + ".txt";
            if (isDelete)
            {
                if (File.Exists(filename))
                    File.Delete(filename);
            }
            else
            {
                UtilityFunction.LockExtension(() =>
                {
                    File.WriteAllText(filename, logContext);
                });
            }
        }

        /// <summary>
        /// 单文件写入
        /// </summary>
        /// <param name="logContext">要写入的内容</param>
        /// <param name="path">路径</param>
        /// <param name="filename">文件名</param>
        private static string LogGetTxtSingle(string filename, string fileServerPath = "")
        {
            string content = string.Empty;

            var dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine + FileDirectory + StaticVar.PathSplitLine;
            if (string.IsNullOrEmpty(fileServerPath) == false)
                dirBase = fileServerPath;
            if (Directory.Exists(dirBase) == false)
                Directory.CreateDirectory(dirBase);

            filename = dirBase + filename + ".txt";
            if (System.IO.File.Exists(filename))
                content = File.ReadAllText(filename);

            return content;
        }
        /// <summary>
        /// 单文件写入
        /// </summary>
        /// <param name="logContext">要写入的内容</param>
        /// <param name="path">路径</param>
        /// <param name="filename">文件名</param>
        private static SmsInfoParam DeleteTxtSingle(string groupId, string fileServerPath = "")
        {
            SmsInfoParam result = null;

            if (string.IsNullOrEmpty(groupId))
                return result;

            var dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine + FileDirectory + StaticVar.PathSplitLine;
            if (string.IsNullOrEmpty(fileServerPath) == false)
                dirBase = fileServerPath;
            if (Directory.Exists(dirBase) == false)
                return result;

            var filename = dirBase + groupId + ".txt";
            if (System.IO.File.Exists(filename))
            {
                result = ReadSms(groupId);
                System.IO.File.Delete(filename);
            }
               
            return result;
        }

    }

    public class StaticVar
    {
        public static string LogThresholdFile = "阈值提醒";
        /// <summary>
        /// 得到当前http请求的目录
        /// </summary>
        public static string HttpPath
        {
            get
            {
                var path = AppContext.BaseDirectory;
                if (path.EndsWith("/"))
                    return path.TrimEnd('/');
                else if (path.EndsWith(@"\"))
                    return path.TrimEnd('\\');
                else
                    return path;
            }
        }

        public static string PathSplitLine
        {
            get
            {
                var path = AppContext.BaseDirectory;
                if (path.EndsWith("/"))
                    return "/";
                else
                    return @"\";
            }
        }

        public static bool IsCentos
        {
            get
            {
                var path = AppContext.BaseDirectory;
                if (path.EndsWith("/"))
                    return true;
                else
                    return false;
            }
        }
    }

    public static class UtilityFunction
    {
        private static ReaderWriterLockSlim LogWriteLock = new ReaderWriterLockSlim();

        #region 锁扩展

        /// <summary>
        /// 锁扩展
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="IsShowException"></param>
        public static void LockExtension(
                                        System.Action callback, bool IsShowException = false
                                        )
        {
            try
            {
                LogWriteLock.EnterWriteLock();
                callback();
            }
            catch
            {
                if (IsShowException)
                    throw;
            }
            finally
            {
                LogWriteLock.ExitWriteLock();
            }
        }

        #endregion 锁扩展

        #region 循环遍历扩展

        /// <summary>
        /// 循环遍历扩展
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="lst"></param>
        /// <param name="callback"></param>
        public static void ForeachExtension<T>
        (
            this List<T> lst,
            Action callback
        )
        {
            try
            {
                callback();
            }
            catch (Exception ex)
            {
                //ex.ToJson().LogWriteService(LogServiceCore.LogServiceCore_Exception);
            }
        }

        #endregion 循环遍历扩展

        #region 定时循环

        /// <summary>
        /// 定时循环
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="PollCount">循环多少次</param>
        /// <param name="IntevalSecond">每隔几秒循环一次</param>
        public static void Loop_Poll(
           System.Func<int, Boolean> callback,
           int PollCount,
           int IntevalSecond = 5000
           )
        {
            System.Threading.Thread.Sleep(IntevalSecond);
            var count = 0;
        a:;
            if (callback(count) == false)
            {
                if (count < PollCount)
                {
                    count = count + 1;
                    System.Threading.Thread.Sleep(IntevalSecond);
                    goto a;
                }
            }
        }

        #endregion 定时循环


        private static ReaderWriterLockSlim LogRequestLog = new ReaderWriterLockSlim();

        #region 请求锁扩展

        /// <summary>
        /// 请求锁扩展
        /// </summary>
        /// <param name="callback"></param>
        /// <param name="IsShowException"></param>
        public static void LockExtensionRequest(
                                        System.Action callback, bool IsShowException = false
                                        )
        {
            try
            {
                LogRequestLog.EnterWriteLock();
                callback();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                LogRequestLog.ExitWriteLock();
            }
        }

        #endregion 锁扩展
    }
}
